package com.lc.projects.unit.thread.part06.test1;

import java.util.concurrent.atomic.AtomicIntegerArray;

//原子数组
public class Test9 {
	public static void main(String[] args) {
		final int THREADS = 100;
		AtomicIntegerArray vector = new AtomicIntegerArray(1000);

		Incrementer incrementer = new Incrementer(vector);
		Decrementer decrementer = new Decrementer(vector);

		Thread[] threadIncrementers = new Thread[THREADS];
		Thread[] threadDecrementers = new Thread[THREADS];

		for (int i = 0; i < THREADS; i++) {
			threadIncrementers[i] = new Thread(incrementer);
			threadDecrementers[i] = new Thread(decrementer);
			threadIncrementers[i].start();
			threadDecrementers[i].start();
		}

		for (int i = 0; i < THREADS; i++) {
			try {
				threadIncrementers[i].join();
				threadDecrementers[i].join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		for (int i = 0; i < vector.length(); i++) {
			if (vector.get(i) != 0) {
				System.out.println("Vector[" + i + "]:" + vector.get(i));
			}
		}
		System.out.println("Main:End.");
	}
}

class Incrementer implements Runnable {

	private AtomicIntegerArray vector;

	public Incrementer(AtomicIntegerArray vector) {
		super();
		this.vector = vector;
	}

	@Override
	public void run() {
		for (int i = 0; i < vector.length(); i++) {
			vector.getAndIncrement(i);
		}
	}
}

class Decrementer implements Runnable {
	private AtomicIntegerArray vector;

	public Decrementer(AtomicIntegerArray vector) {
		super();
		this.vector = vector;
	}

	@Override
	public void run() {
		for (int i = 0; i < vector.length(); i++) {
			vector.getAndDecrement(i);
		}

	}

}
